package com.cbtx.networklib.bean

import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import java.io.IOException

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/7/1 9:59 AM
 * desc   :
 */
class PostJsonBody(val content: String?) : RequestBody() {

    private var contentLength = -1L

    override fun contentType() = CONTENT_TYPE

    @Throws(IOException::class)
    override fun contentLength(): Long {
        var result = contentLength
        if (result == -1L) {
            result = writeOrCountBytes(null, true)
            contentLength = result
        }
        return result
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        writeOrCountBytes(sink, false)
    }

    @Throws(IOException::class)
    private fun writeOrCountBytes(sink: BufferedSink?, countBytes: Boolean): Long {
        var byteCount = 0L
        val buffer: Buffer = if (countBytes) Buffer() else sink!!.buffer

        val bytes = (content ?: "").toByteArray()
        buffer.write(bytes, 0, bytes.size)

        if (countBytes) {
            byteCount = buffer.size
            buffer.clear()
        }

        return byteCount
    }

    companion object {

        private val CONTENT_TYPE: MediaType = "application/json".toMediaType()

        @JvmStatic
        fun create(map: Map<*, *>): PostJsonBody {
            return if (map.isNotEmpty()) {
                PostJsonBody(Gson().toJson(map))
            } else PostJsonBody("")
        }
    }
}
